#include "reg52.h"
#include "4X4MatrixKeyboard.h"
#include "Motor28BYJ48.h"
#include "Stc89c52Eeprom.h"
#include "Lcd1602.h"
#include "string.h"
#include "stdio.h"

sbit led=P2^0;
unsigned int TIME1MS=0;//定时器时间为1毫秒加1
void Time0Init()
{
	TMOD|=0x01;
	TH0=0xfc;
	TL0=0x18;
	ET0=1;
	EA=1;
	TR0=1;
}
void main()
{
	char CorrectPassword[]={'f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f'};
	char EnterPassword[]={'f','f','f','f','f','f','f','f','f','f','f','f','f','f','f','f'};
	char i,ii;
	char yz=0;//验证密码对不对
	char ceshi[100];

	Time0Init();
	Lcd1602Init();

	Lcd1602StaticShow(0,"Hello,Welcome.");
	while(1)
	{
		//如果按键为* 则开始输入密码
		if(KeyboardKeyDown(1)==0x0e)
		{
			Lcd1602StaticShow(0,"Enter Your PIN.");
			Lcd1602Write(0,0x40+0x80);
			//输入密码
			for(i=0;i<16;i++)
			{
				GPIO_KEY=0x0f;
				TIME1MS=0;
				while((TIME1MS<2000)&&(GPIO_KEY==0x0f));
				if(GPIO_KEY!=0x0f)
				{
					EnterPassword[i]=KeyboardKeyDown(0);
					if(EnterPassword[i]=='e')
					{
						i-=1;
						continue;
					}
					if(EnterPassword[i]=='f')break;
					Lcd1602Write(1,EnterPassword[i]);
				}
				else
				{
					break;
				}
			}
			//判断密码对不对
			yz=1;
			for(i=0;i<16;i++)
			{
				if(EnterPassword[i]!=CorrectPassword[i])
				{
					yz=0;
					break;
				}
			}

			//密码正确
			if(yz)
			{
				Lcd1602StaticShow(0,"PIN Correct.");
				TIME1MS=0;
				while(TIME1MS<2000)Motor28BYJ48Drive(0);
			}
			else
			{
				Lcd1602StaticShow(0,"PIN Error.");
				TIME1MS=0;
				while(TIME1MS<2000);
			}

			//初始化
			//ISP_CONTR=0xa0;

			Lcd1602StaticShow(0,"Hello,Welcome.");
			for(i=0;i<16;i++)EnterPassword[i]='f';
		}

		//如果按下a就修改密码
		if(KeyboardKeyDown(1)==0x0a)
		{
			Lcd1602StaticShow(0,"Enter Your PIN.");
			Lcd1602Write(0,0x40+0x80);
			for(i=0;i<16;i++)
			{
				GPIO_KEY=0x0f;
				TIME1MS=0;
				while((TIME1MS<2000)&&(GPIO_KEY==0x0f));
				if(GPIO_KEY!=0x0f)
				{
					EnterPassword[i]=KeyboardKeyDown(0);
					if(EnterPassword[i]=='f')break;
					Lcd1602Write(1,EnterPassword[i]);
				}
				else
				{
					break;
				}
			}
			//写入新密码
			Stc89c52EepromEraseSector(0x2000);
			for(i=0;i<16;i++)Stc89c52EepromWrite(0x2000+i,EnterPassword[i]);
			for(i=0;i<16;i++)CorrectPassword[i]=EnterPassword[i];
			Lcd1602StaticShow(0,"Modify OK.");
			//还原
			for(i=0;i<16;i++)EnterPassword[i]='f';
			TIME1MS=0;
			while(TIME1MS<2000);
			Lcd1602StaticShow(0,"Hello,Welcome.");
		}
		if(KeyboardKeyDown(1)==0x0d)
		{
			//显示密码
			Lcd1602Write(0,0x01);
			for(i=0;i<16;i++)CorrectPassword[i]=Stc89c52EepromRead(0x2000+i);
			for(i=0;i<16;i++)Lcd1602Write(1,CorrectPassword[i]);
			TIME1MS=0;
			while(TIME1MS<2000);
			Lcd1602StaticShow(0,"Hello,Welcome.");
		}
	}
}

void Time0() interrupt 1
{
	TH0=0xfc;
	TL0=0x18;
	TIME1MS++;
	if(TIME1MS>=60000)
	{
		TIME1MS=0;
	}
}
